var express = require('express')
var router=express.Router()
var pool = require('../config/mysqlconfig');
// 获取数据
// http://localhost:3000/cate/all
router.get('/all',function(req,res){
    pool.getConnection(function(err,conn){
      if(err){
        console.log(err)
      }else{
        let sql = "select * from cate"
        conn.query(sql,function(error,results){
          if(error){
            console.log("数据库连接失败")
          }
          res.send(results)
          conn.release()
        })
      }
    })
})

// 添加数据
// http://localhost:3000/cate/add
router.post("/add",function(req,res){
    pool.getConnection(function(err,conn){
      if(err){
        console.log(err)
      }else{
        let name = req.body.c_name;
        let create = new Date();
        let update = new Date();
      
        let data={
          c_name:name,
          create_at:create,
          updated_at:new Date(update),
        }
        let sql = 'insert into cate set ?'
  
        conn.query(sql,data,function(error,results){
          if(error){
            console.log("数据库连接失败")
          }
          res.send(results)
          conn.release()
        })
      }
    })
  })
  // 删除数据
  // http://localhost:3000/article/del
  
  router.delete('/del',function(req,res){
    pool.getConnection(function(err,conn){
      if(err){
        console.log(err)
      }else{
        let id = req.body.id;
        let sql = " delete from cate where id=?"
        conn.query(sql,id,function(error,results){
          if(error){
            console.log(error)
          }
          res.send(results)
          conn.release()
        })
      }
    })
  })
  // 更新数据
  // http://localhost:3000/admin/del
  router.put('/update',function(req,res){
    pool.getConnection(function(err,conn){
      if(err){
        console.log(err)
      }else{
        let name = req.body.c_name;
        let id = req.body.id;
        let update = new Date();
        let data=[name,update,id]
        let sql = "update cate set c_name=?,updated_at=? where id=?"
  
        conn.query(sql,data,function(error,results){
          if(error){
            console.log(error)
          }
          res.send(results)
          conn.release()
        })
      }
    })
  })
  
  // 查找数据
  // http://localhost:3000/admin/select
  router.post('/sel',function(req,res){
    pool.getConnection(function(err,conn){
        if(err){
            console.log(err)
        }else{
            let id = req.body.id
            let sql = "select * from cate where id=?"
            conn.query(sql,id,function(error,results){
                if(error){
                    console.log(error)
                }
                res.send(results)
                conn.release()
            })
        }
    })
  })

module.exports = router